import axios from "axios";
import qs from 'qs'

var url = "";

// 创建axios实例
const service = axios.create({
    baseURL: url, // api的base_url
    timeout: 30000, // 请求超时时间 30000
    headers: {
        // 'Content-Type': 'application/x-www-form-urlencoded'
        // 'Content-Type': 'application/json'
    }
});

// request拦截器
service.interceptors.request.use(
    config => {
        console.log(config, "请求参数");
        // config.headers['X-Token'] = localStorage.getItem('token');
        // config.headers['Content-Type'] = config.headers['Content-Type'] || 'application/x-www-form-urlencoded';
        config.headers['Content-Type'] = config.headers['Content-Type'] || 'application/json';
        config.data = qs.stringify(config.data);
        if (config.headers['Content-Type'] != "multipart/form-data") {
            config.data = qs.stringify(config.data);
        }

        return config;
    },
    error => {
        Promise.reject(error);
    }
);

// respone拦截器
service.interceptors.response.use(
    response => {
        console.log(response, "===response====");
        const result = response.data;
        console.log("code:" + result.Code);

        var errMsg = "";

        switch (result.Code) {
            case 2:
                console.log("resolve");
                return Promise.resolve(response.data);
                break;
            case 1001:
                errMsg = "需要权限,请先登陆";
                break;
            default:
                errMsg = result.Message;
                break;
        }
        if (errMsg.length > 0) {

            //隐藏mask
            if (result.resultCode == 1001) {
                window.location.href = "/login.html";
            } else {
                // alert(errMsg);
            }
        }
        return Promise.reject(result);
    },
    error => {
        let ErrorMsg = error.message;
        if (error.code == "ECONNABORTED") ErrorMsg = "请求超时，请稍后再试。";
        return Promise.reject(error);
    }
);

export default service;
